package com.mz.common.interceptor;

import com.mz.common.dto.UserHolderDto;
import com.mz.common.utils.JwtUtils;
import com.mz.common.utils.UserHolder;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInfoInterceptor extends HandlerInterceptorAdapter {

    /**
     * 前置拦截
     * **/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        if( token == null ){
            return true;
        }
        Claims claims = JwtUtils.parseJWT(token);
        String userId = claims.getSubject();
        if( userId != null ){
            userId = userId.split(":")[0];
            UserHolderDto userHolderDto = new UserHolderDto();
            userHolderDto.setId( Long.valueOf(userId) );
            UserHolder.saveUser(userHolderDto);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }
}
